package org.teststack.token;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TokenManager {
    private Map<String, Token> tokens = new HashMap<>();
    private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public String createToken(String tokenId, long ttlInSeconds) {
        long expirationTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(ttlInSeconds);
        Token token = new Token(tokenId, expirationTime);
        tokens.put(tokenId, token);

        // 模拟定时检查
        scheduler.schedule(() -> checkTokenExpiration(token), ttlInSeconds, TimeUnit.SECONDS);

        return tokenId;
    }

    private void checkTokenExpiration(Token token) {
        if (token.isExpired()) {
            System.out.println("Token " + token.getTokenId() + " has expired.");
            // 这里可以添加处理过期Token的逻辑，比如从存储中移除等
            tokens.remove(token.getTokenId());
        }
    }

    // 用于测试的方法
    public boolean isValidToken(String tokenId) {
        return tokens.containsKey(tokenId) && !tokens.get(tokenId).isExpired();
    }

    // 停止计划任务
    public void shutdown() {
        scheduler.shutdown();
    }
}
